package com.sgb.kjwl.view.ui.activity.packers;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.gson.Gson;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.aspectj.login.LoginCheck;
import com.sgb.kjwl.databinding.AtEmploymentDetailBinding;
import com.sgb.kjwl.di.packers.DaggerPackersComponent;
import com.sgb.kjwl.di.packers.PackersModule;
import com.sgb.kjwl.model.entity.self.SelfEmploymentEditEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.DialogHelper;
import com.sgb.kjwl.utils.NumberConstant;
import com.sgb.kjwl.utils.WebJsConstants;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.ui.activity.WebViewX5Fragment;
import com.sgb.kjwl.view.ui.activity.pick.PickInquireByLetterActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.CertificationActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.widget.PackerEmploymentShareDialog;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.kjwl.viewmodel.packers.EmploymentDetailModel;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.base.di.AppComponent;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.tencent.smtt.sdk.WebSettings;

import javax.inject.Inject;

/**
 * 临时用工详情
 *
 * @author liWei
 * @date 2020/11/11
 */
@Route(path = AppRouteConstant.GongDui.ROUTER_PATH_EMPLOYMENTDETAILACTIVITY)
public class EmploymentDetailActivity extends AppActivity {

    private AtEmploymentDetailBinding binding;
    @Inject
    EmploymentDetailModel viewModel;

    private final static int REQUEST_CODE = 10031;
    private RoundCornerDialog roundCornerDialog;
    private boolean success;
    private String mUserNo, userNo, no;
    private int employmentType = -1;
    private boolean mIsFollow = false;
    private boolean isApply;

    public static void start(Context context, String no, String teamName, boolean isApply) {
        Intent intent = new Intent();
        intent.setClass(context, EmploymentDetailActivity.class);
        intent.putExtra("no", no);
        intent.putExtra("teamName", teamName);
        intent.putExtra("isApply", isApply);
        context.startActivity(intent);
    }

    public static void startForResult(Activity context, String no, String teamName, boolean isApply, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(context, EmploymentDetailActivity.class);
        intent.putExtra("no", no);
        intent.putExtra("teamName", teamName);
        intent.putExtra("isApply", isApply);
        context.startActivityForResult(intent, requestCode);
    }

    public static void startForResult(Fragment context, String no, String teamName, boolean isApply, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(context.getContext(), EmploymentDetailActivity.class);
        intent.putExtra("no", no);
        intent.putExtra("teamName", teamName);
        intent.putExtra("isApply", isApply);
        context.startActivityForResult(intent, requestCode);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPackersComponent.builder().appComponent(appComponent).packersModule(new PackersModule(this)).build().inject(this);
    }

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActionBar.setOnBackClickListener(v -> {
            if (success) {
                Intent intent = new Intent();
                intent.putExtra("isFocus", mIsFollow);
                intent.putExtra("isApply", isApply);
                setResult(1, intent);
            }
            finish();
        });
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.at_employment_detail);

        userNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        no = getIntent().getStringExtra("no");

        binding.setViewModel(viewModel);
        binding.linAttention.setOnClickListener(this);
        binding.linIm.setOnClickListener(this);
        binding.linHanxun.setOnClickListener(this);
        binding.linShare.setOnClickListener(this);
        binding.btnApply.setOnClickListener(this);

        viewModel.detailEmployment(getIntent().getStringExtra("no"));

    }

    @Override
    protected void init() {
        viewModel.getH5Url(getIntent().getStringExtra("no"));
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.lin_attention) {
            followCheck();
        } else if (id == R.id.lin_im) {
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                VerificationCodeLoginActivity.start(getActivity(), false);
            } else {
                if (employmentType == -1){
                    return;
                }

                if (employmentType == 0) {
                    MToast.showToast(this, "该信息为个人用户发布，当前无法交流");
                    return;
                }

                if (mUserNo.equals(userNo)) {
                    MToast.showToast(this, "不能和自己交流");
                } else {
                    viewModel.detailEmploymentIm(getIntent().getStringExtra("no"));
                }
            }
        } else if (id == R.id.lin_hanxun) {
            sendNote();
        } else if (id == R.id.lin_share) {
            share();
        } else if (id == R.id.btn_apply) {
            apply();
        }
    }

    public void getUrl(String url) {
        binding.progress.show();
        binding.progress.setColor(ContextCompat.getColor(this, R.color.translucent));
        binding.webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        binding.webView.getSettings().setDomStorageEnabled(true);
        binding.webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        binding.webView.getSettings().setAppCacheEnabled(true);
        binding.webView.loadUrl(url);
        //打电话
        binding.webView.registerHandler(WebJsConstants.GO_TO_PHONE, (data, function) -> {
            String id = new Gson().fromJson(data, WebViewX5Fragment.TitleEntity.class).getId();
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                VerificationCodeLoginActivity.start(getActivity(), false);
            } else {
                if (mUserNo != null && mUserNo.equals(userNo)) {
                    MToast.showToast(this, "不能拨打自己的电话");
                } else {
                    showDialog(id);
                }
            }
        });
        binding.webView.registerHandler(WebJsConstants.JUDGE_CALL_PHON, (data, function) -> {
            String id = new Gson().fromJson(data, WebViewX5Fragment.TelEntity.class).getTel();
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_WEB_VIEW_JUMP);
            } else {
                if (SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                    showDialog(id);
                } else {
                    showDialog();
                }
            }

        });
    }

    public void detailEmploymentShare(SelfEmploymentEditEntity data, String url) {
        PackerEmploymentShareDialog dialog = PackerEmploymentShareDialog.newInstance(data, url);
        dialog.showAllowingLoss(getSupportFragmentManager(), "packerEmploymentShareDialog");
    }

    public void detailEmploymentIm(SelfEmploymentEditEntity data) {
        if (!TextUtils.isEmpty(data.getImId())) {
            viewModel.findCustomerServiceImAccount(data.getImId());
        } else {
            MToast.showToast(this, "未设置客服人员，无法交流！");
        }
    }

    public void detailEmploymentApply(SelfEmploymentEditEntity data) {
        if (TextUtils.isEmpty(data.getCategoryName())) {
            MToast.showToast(this, "该用工暂时不支持报名");
        } else {
            ActivityJump.jumpToActivityForResult(EmploymentDetailActivity.this, EmploymentApplyActivity.class, REQUEST_CODE
                    , Pair.create("no", getIntent().getStringExtra("no")), Pair.create("entity", data));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                success = true;
                isApply = true;
                viewModel.getH5Url(getIntent().getStringExtra("no"));
                binding.btnApply.setBackgroundResource(R.drawable.shape_btn_apply_frame_build_checked_detail);
                binding.btnApply.setClickable(false);
                binding.btnApply.setText("已报名");
            }
        }
    }

    public void onBackAccount(String msg) {
        IMUtils.getInstance().buildSingleTalking(msg);
    }

    public void detailEmployment(SelfEmploymentEditEntity data) {
        if (!TextUtils.isEmpty(userNo) && data != null && userNo.equals(data.getUserNo())) {
            binding.linDetailTool.setVisibility(View.GONE);
        } else {
            binding.linDetailTool.setVisibility(View.VISIBLE);
        }

        if (data != null) {
            mUserNo = data.getUserNo();
            employmentType = data.getIsCompany();
            mIsFollow = data.isFocus();
            isApply = data.isApply();
        }

        if (!mIsFollow) {
            binding.ivAttention.setImageResource(R.mipmap.img_gary_heart);
            binding.tvAttention.setTextColor(ContextCompat.getColor(EmploymentDetailActivity.this, R.color.color_666666));
            binding.tvAttention.setText("关注");
        } else {
            binding.ivAttention.setImageResource(R.mipmap.gz_orange);
            binding.tvAttention.setTextColor(ContextCompat.getColor(EmploymentDetailActivity.this, R.color.color_EF4033));
            binding.tvAttention.setText("已关注");
        }

        if (isApply) {
            binding.btnApply.setBackgroundResource(R.drawable.shape_btn_apply_frame_build_checked_detail);
            binding.btnApply.setClickable(false);
            binding.btnApply.setText("已报名");
        }else {
            binding.btnApply.setBackgroundResource(R.drawable.red_color_change_radius_5);
            binding.btnApply.setClickable(true);
            binding.btnApply.setText("立即报名");
        }
    }

    //打电话
    public void showDialog(String phone) {
        if (roundCornerDialog == null) {
            View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
            roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
            roundCornerDialog.setCanceledOnTouchOutside(false);

            TextView tvMessage = view.findViewById(R.id.tv_message);
            TextView tvTitle = view.findViewById(R.id.tv_title);
            TextView tvLogoutConfirm = view.findViewById(R.id.tv_logout_confirm);
            tvTitle.setVisibility(View.VISIBLE);
            TextView tvLogoutCancel = view.findViewById(R.id.tv_logout_cancel);
            tvTitle.setText("确认呼叫");
            tvMessage.setText(phone);

            //确定
            tvLogoutConfirm.setOnClickListener(v -> {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + phone);
                intent.setData(data);
                getActivity().startActivity(intent);

                roundCornerDialog.dismiss();
            });

            //取消
            tvLogoutCancel.setOnClickListener(v -> roundCornerDialog.dismiss());
        }
        if (!roundCornerDialog.isShowing()) {
            roundCornerDialog.show();
        }
    }

    public void showDialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);

        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        tv_title.setVisibility(View.VISIBLE);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        tv_title.setText("提示");
        tv_message.setText("你需要进行认证后才能操作，去认证");

        //确定
        tv_logout_confirm.setOnClickListener(v -> {
            CertificationActivity.start(getActivity());
            roundCornerDialog.dismiss();
        });

        //取消
        tv_logout_cancel.setOnClickListener(v -> roundCornerDialog.dismiss());
    }

    @Override
    public void onBackPressed() {
        if (success) {
            Intent intent = new Intent();
            intent.putExtra("isFocus", mIsFollow);
            intent.putExtra("isApply", isApply);
            setResult(1, intent);
        }
        super.onBackPressed();
    }

    public void follow() {
        success = true;
        NumberConstant.sIsChangeForTeam = 1;
        if (!mIsFollow) {
            binding.ivAttention.setImageResource(R.mipmap.gz_orange_no_select);
            binding.tvAttention.setTextColor(ContextCompat.getColor(EmploymentDetailActivity.this, R.color.color_666666));
            binding.tvAttention.setText("关注");
        } else {
            binding.ivAttention.setImageResource(R.mipmap.gz_orange);
            binding.tvAttention.setTextColor(ContextCompat.getColor(EmploymentDetailActivity.this, R.color.color_EF4033));
            binding.tvAttention.setText("已关注");
        }
    }

    @LoginCheck
    public void share(){
        viewModel.getShareH5Url(getIntent().getStringExtra("no"));
    }

    @LoginCheck(needRealName = true)
    public void sendNote(){
        if (mUserNo.equals(userNo)) {
            MToast.showToast(this, "不能给自己发送函询");
        } else {
            String teamName = getIntent().getStringExtra("teamName");
            PickInquireByLetterActivity.start(EmploymentDetailActivity.this, no, "team", "", "", "3", teamName);
        }
    }

    @LoginCheck(needRealName = true)
    public void followCheck(){
        if (userNo.equals(mUserNo)) {
            MToast.showToast(this, "不能关注自己发布的信息");
        } else {
            mIsFollow = !mIsFollow;
            viewModel.followForTeam(no, "4", mIsFollow);
        }
    }

    @LoginCheck(needRealName = true)
    public void apply(){
        if (userNo.equals(mUserNo)) {
            MToast.showToast(this, "自己不能报名自己发布的临时用工");
        } else {
            if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 0){
                viewModel.detailEmploymentApply(getIntent().getStringExtra("no"));
            }else {
                MToast.showToast(this, "个人身份才能报名");
            }
        }
    }
}


